<?php
/**
*
*	后台首页暨管理程序 @zairwolf
*	2009-4-16 init edit 2009-4-22 8:07 ok
*	2009-4-21 分离admin的菜单结构 ok
*	2009-4-21 去掉_log函数 ok
*	2009-4-28 增加权限的检测 23:38 ok
*	2009-4-28 由于user_admin添加账号可缺省密码的原因，后台pswd改为2次md5 23:34 ok 
*
*/

define('IN_ACP', true);
require_once '../include/init.php';
require_once ROOT.'admin/global.func.php';

$frame=_get_post('frame');
$ptype=_get_post('ptype');
$pfile=_get_post('pfile');

//--------------------------------------------------------------------------//
//																			//
//								日志记录									//
//																			//
//--------------------------------------------------------------------------//
//不记录密码
$_tmp_pswd = $_tmp_new_pswd = $_tmp_repeat_pswd = '';
if(!empty($_POST['admin_pswd'])) {
	$_tmp_pswd = $_POST['admin_pswd'];
	$_POST['admin_pswd'] = '*****';
}
if(!empty($_POST['admin_new_pswd'])) {
	$_tmp_new_pswd = $_POST['admin_new_pswd'];
	$_POST['admin_new_pswd'] = '*****';
}
if(!empty($_POST['admin_repeat_pswd'])) {
	$_tmp_repeat_pswd = $_POST['admin_repeat_pswd'];
	$_POST['admin_repeat_pswd'] = '*****';
}

//记录所有提交
$cols=array(
	'user_id' => $_G['user_id'],
	'user_name' => $_G['user_name'],
	'acp_id' => '',#暂时无法记录
	'acp_name' => '',
	'info' => base64_encode(serialize(array($_GET,$_POST))),
	'dateline' => TIMESTAMP,
);
$id = db_i("insert into rd8_log set ".sqlcol($cols));//本记录为后台必备常规记录，和addLog函数不同

//对密码的保护还原
if(!empty($_tmp_pswd)) {
	$_POST['admin_pswd'] = $_tmp_pswd;
}
if(!empty($_tmp_new_pswd)) {
	$_POST['admin_new_pswd'] = $_tmp_new_pswd;
}
if(!empty($_tmp_repeat_pswd)) {
	$_POST['admin_repeat_pswd'] = $_tmp_repeat_pswd;
}
unset($_tmp_pswd, $_tmp_new_pswd, $_tmp_repeat_pswd);

//--------------------------------------------------------------------------//
//																			//
//								快捷保存									//
//																			//
//--------------------------------------------------------------------------//
//设置快捷cookie保存
if(!$shortcut = _cookie('quickpfile'.$_G['user_id'])) $shortcut = array();
if($ptype && $pfile) {
	array_unshift($shortcut, $ptype.'||'.$pfile);
	array_unshift($shortcut, 'default||home');
	$shortcut = array_unique($shortcut);
	while(count($shortcut) > 10) {
		array_pop($shortcut);
	}
	cookie('quickpfile'.$_G['user_id'], $shortcut, 864000);
}

//--------------------------------------------------------------------------//
//																			//
//								登录处理									//
//																			//
//--------------------------------------------------------------------------//
//设置后台程序的模板地址
$_assign['pfile'] = $pfile;
$_assign['ptype'] = $ptype;

//清理acp session过期
if(!$_SYSTEM['SAFE']['acp_expire']) $_SYSTEM['SAFE']['acp_expire'] = 15;
db_q('DELETE FROM rd8_session_acp WHERE lasttime < '.(TIMESTAMP-$_SYSTEM['SAFE']['acp_expire']*60));

$adminsess = $isfounder = '';
$adminpriv = $adminhistory = array();

login();
if(!$admin = db_r("select * from rd8_user_acp where user_id='$_G[user_id]'")) b('您无权访问后台');

if($admin['isfounder']) $isfounder = true;
$needchangepswd = !acppriv() && $admin['changepswdtime'] <= TIMESTAMP;
if($needchangepswd) $adminhistory = explode(',', $admin['history']);

$isLogin = false;

if($adminsess = db_r("select * from rd8_session_acp where acp_id='$admin[id]'")) {
	$isLogin = true;
	if($action == 'logoff') {
		db_q("delete from rd8_session_acp where acp_id='$admin[id]'");
		header('Location: '.$_SYSTEM['SYSTEM']['SITE_ADDR']);
		exit;
	}
	if($adminsess['isfounder']) $isfounder = true;
	else $adminpriv = explode(',', $adminsess['privilege']);
}

if(!$isLogin) {//用户登录
	$admin_name = _post('admin_name');
	$admin_pswd = _post('admin_pswd');
	if($admin_name && $admin_pswd) {//用户后台登录
		$admin_pswd = md5(md5($admin_pswd));
		if(!$admin = db_r("select * from rd8_user_acp where name='$admin_name'")) b('登录账号不存在');
		//IP和旧密码检查
		if($admin['accessip'] && !ipAccess($admin['accessip'], false)) {//IP禁止
			b('登录IP不在该账号中的允许范围之内');
		}elseif($admin['pswd'] != $admin_pswd) {//旧密码错误
			//增加日志记录
			if(strlen($_POST['admin_pswd'])>4) $logpwd=substr($_POST['admin_pswd'],0,2)."...".substr($_POST['admin_pswd'],-2);
			else $logpwd=substr($_POST['admin_pswd'],0,1)."...".substr($_POST['admin_pswd'],-1);
			//暂未记录

			db_q("update rd8_user_acp set error=error+1 WHERE id='$admin[id]'");

			b('登录密码错误');
		}
		//新增检查user_id是否等于后台的user_id 2009-4-22 13:43 @zairwolf
		if($_G['user_id']<>$admin['user_id']) b('后台登录账号和前台不符');
		//更新用户后台密码资料
		db_q("update rd8_user_acp SET lastlogin='".TIMESTAMP."', lastloginip='$_G[user_ip]' WHERE id='$admin[id]'");
		db_q("REPLACE INTO rd8_session_acp set acp_id='$admin[id]',acp_name='$admin[name]',user_id='$_G[user_id]',privilege='$admin[privilege]',isfounder='$admin[isfounder]',lasttime=".TIMESTAMP);

		j($_SYSTEM['SYSTEM']['SITE_ADDR'].'/admin/'.(empty($_POST['requestring']) ? '' : '?'.$_POST['requestring']), '登录成功');

	}else {//显示登录页面
		acpheader();
		$tpl = new Tpl('frame_login');
		$tpl->assign('U_adminname', $_G['user_name']);
		$tpl->assign('C_querystring',empty($_SERVER['QUERY_STRING']) ? '' : $_SERVER['QUERY_STRING']);
		$tpl->output();
		acpfooter();
	}

}elseif($needchangepswd || $action == 'changepswd') {//密码过期||主动修改
	$admin_name = empty($_POST['admin_name']) ? '' : _addslashes($_POST['admin_name']);
	$admin_new_pswd = empty($_POST['admin_new_pswd']) ? '' : md5(md5($_POST['admin_new_pswd']));
	$admin_repeat_pswd = empty($_POST['admin_repeat_pswd']) ? '' : md5(md5($_POST['admin_repeat_pswd']));

	if($admin_name && $admin_new_pswd) {//更换提交
		$admin = '';
		if(!$admin = db_r("select * from rd8_user_acp where name='$admin_name'")) b('未知后台用户');
		if(strlen($_POST['admin_new_pswd']) < $_SYSTEM['SAFE']['acp_pswd_minlength']) b('密码长度不对');//密码长度不对
		$adminhistory[] = md5($admin['pswd']);//历史记录密码3次md5加密，安全起见
		while(count($adminhistory) > $_SYSTEM['SAFE']['acp_pswd_history']) array_pop($adminhistory);
		if(in_array(md5($admin_new_pswd), $adminhistory)) b('不得使用曾使用过的密码');
		db_q("update rd8_user_acp set pswd='$admin_new_pswd', history='".implode(',', $adminhistory)."', changepswdtime='".(TIMESTAMP+$_SYSTEM['SAFE']['acp_pswd_expire']*86400)."' WHERE name='$admin_name'");

		j($_SYSTEM['SYSTEM']['SITE_ADDR'].'/admin/'.(empty($_POST['requestring']) ? '' : '?'.$_POST['requestring']), '密码修改成功');

	}else {//显示需要更换页面
		acpheader();
		$tpl = new Tpl('frame_changepswd');
		$tpl->assign('U_adminname', $admin['name']);
		$tpl->assign('C_forcechange', $action != 'changepswd');
		$tpl->assign('C_querystring',empty($_SERVER['QUERY_STRING']) ? '' : $_SERVER['QUERY_STRING']);
		$tpl->output();
		acpfooter();
	}
}



//--------------------------------------------------------------------------//
//																			//
//								菜单生成									//
//																			//
//--------------------------------------------------------------------------//
require_once ROOT.'admin/menu.cfg.php';
$acpmenu = acpmenu();
$acpcate = array_keys($acpmenu);
$acpdefaultmenu = $acporidefault = acpdefaultmenu();

// $m 大菜单 $k 内容块 $f 功能
if(!$isfounder) {//过滤大类权限
	foreach($acpcate as $mp => $m) {//-------------遍历分类-----------
		if(!acppriv($m) && $m != 'default') {// 没有大类权限
			unset($acpcate[$mp]);
			unset($acpmenu[$m]);
			continue;
		}
		$first = $m!='default';// 第一个有权项
		foreach($acpmenu[$m] as $k => $fs) {//--------------------遍历栏目块--------------fs为array
			if(acppriv($m, $k) || $k == 'shortcut') {// 有功能块权限
				foreach($fs as $p => $f) {//---------遍历栏目$p为索引 $f为索引名称-----------
					if(acppriv($m, $k, $p)) {// 有权限
						if($p == $acporidefault[$m] || $first) {// 预设默认或者第一个
							$acpdefaultmenu[$m] = $p;// 设置默认
							$first = false;
						}
					}else {
						unset($acpmenu[$m][$k][$p]);
					}
				}
			}else {
				unset($acpmenu[$m][$k]);
			}
		}
	}
}


if(!$frame && !$pfile && !$ptype) {//默认显示总框架
	$tpl = new Tpl('frame');
	$tpl->output();
	exit;

}elseif($frame == 'head') {//顶部条
	$tpl = new Tpl('frame_head');

	$catblock = array();
	$cattitleArr=acpcatlang();
	$i = 1;
	krsort($acpcate);
	foreach($acpcate as $category) {
		$catblock[] = array(
			'C_i' => $i++,
			'C_ptype' => $category,
			'C_title' => $cattitleArr[$category],
			//'C_menuon' => $ptype == $category ? ' id="menuon"' : '',
		);
	}
	$tpl->assign('C_catblock',$catblock);
	$tpl->output();
	exit;

}elseif($frame == 'left') {//左侧条
	$lists = $acptitleArr=array();
	$i = $jspfile = 0;
	$cattitleArr=acpcatlang();
	//生成快捷方式栏目临时用的title
	foreach($acpmenu as $key=>$val){
		foreach($val as $val2){
			foreach($val2 as $key2=>$val3){
				$acptitleArr[$key.'_'.$key2]=$val3;
			}
		}
	}
	foreach($acpmenu[$ptype] as $title => $items) {
		$funclist = array();
		if($title == 'shortcut') {
			foreach($shortcut as $val) {
				$val = explode('||', $val);
				$funclist[] = array(
					'C_i' => ++$i,
					'C_name' => $acptitleArr[$val[0].'_'.$val[1]],
					'C_pfile' => $val[1],
					'C_ptype' => $val[0],
					'C_pfileon' => $val[1] == 'home' ? ' id="pfileon"' : '',
				);
			}
			$jspfile = 1;
		}
		foreach($items as $_pfile=>$_pfilename) {
			$funclist[] = array(
				'C_i' => ++$i,
				'C_name' => $_pfilename,
				'C_pfile' => $_pfile,
				'C_ptype' => $ptype,
				'C_pfileon' => $acpdefaultmenu[$ptype] == $_pfile ? ' id="pfileon"' : '',
			);
			$jspfile = $jspfile ? $jspfile : ($acpdefaultmenu[$ptype] == $_pfile ? $i : 0);
		}
		$lists[] = array(
			'C_i' => $i++,
			'C_name' => $cattitleArr[$title],
			'funclist' => $funclist,
			'C_collapsed' => isset($lists[$pfile]) ? ' id="ptypeon"' : '',
		);
	}
	$jspfile = $jspfile ? $jspfile : 1;
	$tpl = new Tpl('frame_left');
	$tpl->assign('lists', $lists);
	$tpl->assign('jspfile', $jspfile);
	$tpl->output();
	exit;
}


//--------------------------------------------------------------------------//
//																			//
//								正常引用									//
//																			//
//--------------------------------------------------------------------------//

acpheader();

if(!$ptype || !in_array($ptype, $acpcate)) {
	b('未知ptype');

}else {
	if(!$pfile || $pfile == 'default') {
		$pfile = $acpdefaultmenu[$ptype];//默认显示的pfile
		$_assign['pfile'] = $pfile;
	}

	//权限检测
	$inarray = false;
	foreach($acpmenu[$ptype] as $key => $val) {
		if(array_key_exists($pfile, $val)) {
			$inarray = true;
			break;
		}
	}
	if(!$inarray && $pfile != 'home') b('对当前栏目您没有访问权限');

	$admfile = acpfile($ptype,$pfile);
	if(!$admfile) $admfile = $pfile;
	$admfilepath = ROOT."admin/{$ptype}_$admfile.php";

	if(!is_file($admfilepath)) b('暂不提供'.$admfilepath);

	require $admfilepath;
}

acpfooter();




